import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Tag,
  Menu,
  Dropdown,
  Badge,
  Divider,
  BackTop,
  message,
  notification,
} from 'antd';
import StandardTableCustom from '../../customComponents/StandardTableCustom';
import OperateModal from './OperateModal';
import PageHeaderWrapperCustom from '../../customComponents/PageHeaderWrapperCustom';
import Ellipsis from '../../components/Ellipsis';

import styles from './List.less';

const FormItem = Form.Item;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const status = [
  {
    key: -10000,
    badge: 'default',
    text: '不限',
    value: -10000,
  },
  {
    key: 2,
    badge: 'success',
    text: '已启用',
    value: 2,
  },
  {
    key: -2,
    badge: 'error',
    text: '已禁用',
    value: -2,
  },
];

@connect(({ warehouse, loading }) => ({
  warehouse,
  loading: loading.models.warehouse,
}))
@Form.create()
class List extends PureComponent {
  state = {
    formValues: {},
    addNewVisible: false,
    updateItemVisible: false,
    metaData: {},
    customData: {
      count: 0,
      list: [],
      pagination: {},
    },
    pageNo: 1,
    pageSize: 10,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    const { pageNo, pageSize } = this.state;
    dispatch({
      type: 'warehouse/list',
      payload: { pageNo, pageSize },
    }).then(() => {
      const {
        warehouse: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  }

  setDefault = record => {
    const { dispatch } = this.props;

    dispatch({
      type: 'warehouse/updateDefault',
      payload: {
        warehouseId: record.warehouseId,
      },
    }).then(() => {
      const {
        warehouse: { data },
      } = this.props;
      const { status: statusCode, message: messageText } = data;
      if (statusCode === 200) {
        message.success(`已将${record.name}设为默认仓库。`);

        const { customData } = this.state;
        const { pagination } = customData;
        const { current } = pagination;
        this.refreshGrid(current);
      } else {
        message.error(messageText);
      }
    });
  };

  setStatus = record => {
    const { dispatch } = this.props;

    dispatch({
      type: 'warehouse/updateStatus',
      payload: {
        warehouseId: record.warehouseId,
        status: record.status === 2 ? -2 : 2,
      },
    }).then(() => {
      const {
        warehouse: { data },
      } = this.props;
      const { status: statusCode, message: messageText } = data;
      if (statusCode === 200) {
        message.success(
          record.status === 2 ? `已将${record.name}设为禁用。` : `已将${record.name}设为启用。`
        );

        const { customData } = this.state;
        const { pagination } = customData;
        const { current } = pagination;
        this.refreshGrid(current);
      } else {
        message.error(messageText);
      }
    });
  };

  showAddNewModal = () => {
    this.setState({
      addNewVisible: true,
    });
  };

  afterAddNewModalOk = () => {
    this.setState({
      addNewVisible: false,
    });
    this.refreshGrid();
  };

  afterAddNewModalCancel = () => {
    this.setState({
      addNewVisible: false,
    });
  };

  afterUpdateItemModalOk = () => {
    this.setState({
      updateItemVisible: false,
    });
    const { customData } = this.state;
    const { pagination } = customData;
    const { current } = pagination;
    this.refreshGrid(current);
  };

  afterUpdateItemModalCancel = () => {
    this.setState({
      updateItemVisible: false,
    });
  };

  deleteItem = record => {
    const { dispatch } = this.props;

    dispatch({
      type: 'warehouse/remove',
      payload: {
        warehouseId: record.warehouseId,
      },
    }).then(() => {
      const {
        warehouse: { data },
      } = this.props;
      const { status: statusCode, message: messageText } = data;
      if (statusCode === 200) {
        notification.success({
          placement: 'bottomRight',
          message: '操作结果',
          description: '数据已经删除成功，请进行后续操作。',
        });

        const { customData } = this.state;
        const { pagination } = customData;
        const { current } = pagination;
        this.refreshGrid(current);
      } else {
        notification.error({
          placement: 'bottomRight',
          message: '操作结果',
          description: messageText,
        });
      }
    });
  };

  cancelDelete = () => {
    message.info('已取消删除操作。');
  };

  handleMenuClick = (e, record) => {
    switch (e.key) {
      case '1':
        this.setDefault(record);
        break;

      case '2':
        this.setStatus(record);
        break;

      default:
        message.warn('未知操作');
    }
  };

  handleEditClick = record => {
    this.setState({ metaData: record });
    this.setState({ updateItemVisible: true });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    // console.dir(pagination);
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'warehouse/list',
      payload: params,
    }).then(() => {
      const {
        warehouse: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { pageSize } = this.state;

    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'warehouse/list',
      payload: {
        pageNo: 1,
        pageSize,
      },
    }).then(() => {
      const {
        warehouse: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  };

  refreshGrid = pageNo => {
    const { dispatch } = this.props;
    const { customData } = this.state;
    const { pagination } = customData;

    const params = {
      pageNo: (pageNo || 1) <= 1 ? 1 : pageNo,
      pageSize: pagination.pageSize,
    };
    dispatch({
      type: 'warehouse/list',
      payload: params,
    }).then(() => {
      const {
        warehouse: { data },
      } = this.props;
      this.setState({ customData: data });
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'warehouse/list',
        payload: {
          ...values,
          pageNo: 1,
          pageSize,
        },
      }).then(() => {
        const {
          warehouse: { data },
        } = this.props;
        this.setState({ customData: data });
      });
    });
  };

  renderSimpleForm() {
    const { form, dispatch } = this.props;
    const { addNewVisible } = this.state;
    const { getFieldDecorator } = form;
    const { category } = this.state;
    const statusOption = [];
    status.forEach(item => {
      const { text, value } = item;
      statusOption.push(
        <Select.Option key={value} value={value}>
          {text}
        </Select.Option>
      );
    });
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          <Col md={6} sm={24}>
            <FormItem label="关键词">
              {getFieldDecorator('keywords')(<Input placeholder="请输入需要搜索的内容" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status', {
                rules: [{ required: false, message: '请选择状态!' }],
                initialValue: status[0].value,
              })(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {statusOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <Divider type="vertical" />
              <Button type="primary" onClick={this.showAddNewModal}>
                新增仓库
              </Button>
              <OperateModal
                visible={addNewVisible}
                mode="add"
                category={category}
                dispatch={dispatch}
                afterOK={this.afterAddNewModalOk}
                afterCancel={this.afterAddNewModalCancel}
              />
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { loading, dispatch } = this.props;
    const { customData, metaData, updateItemVisible, category } = this.state;

    const columns = [
      {
        title: 'Id',
        dataIndex: 'warehouseId',
        width: 80,
        align: 'center',
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 180,
        align: 'left',
        render: (val, record) => {
          const tag =
            record.defaultSet === 1 ? (
              <Tag color="#7a8aa2" style={{ marginLeft: '4px' }}>
                默认
              </Tag>
            ) : (
              ''
            );
          return (
            <Fragment>
              {val}
              {tag}
            </Fragment>
          );
        },
      },
      {
        title: '仓库编号',
        dataIndex: 'code',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '所在地址',
        dataIndex: 'address',
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 120,
        align: 'center',
        filters: status,
        filterMultiple: false,
        onFilter: (value, record) => record.status.toString() === value,
        render(val, record) {
          let badgeValue = '';
          status.forEach(item => {
            const { badge, value } = item;
            if (value === val) {
              badgeValue = badge;
            }
          });
          return <Badge status={badgeValue} text={record.statusNote} />;
        },
      },
      {
        title: '操作',
        width: 156,
        align: 'center',
        render: (text, record) => (
          <Fragment>
            <Dropdown.Button
              size="small"
              onClick={() => this.handleEditClick(record)}
              overlay={
                <Menu onClick={e => this.handleMenuClick(e, record)}>
                  <Menu.Item key="1">
                    <Icon type="setting" />
                    设为默认
                  </Menu.Item>
                  <Menu.Item key="2">
                    <Icon type={record.status === 2 ? 'minus-circle' : 'check-circle'} />
                    {record.status === 2 ? '禁用' : '启用'}
                  </Menu.Item>
                  <Menu.Item key="3">
                    <Icon type="delete" />
                    删除
                  </Menu.Item>
                </Menu>
              }
            >
              <Icon type="edit" />
              编辑
            </Dropdown.Button>
          </Fragment>
        ),
      },
    ];

    return (
      <PageHeaderWrapperCustom title="仓库列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTableCustom
              loading={loading}
              data={customData}
              columns={columns}
              expandedRowRender={record => (
                <div>
                  <p>
                    <span className="bold">名称：</span>
                    <span>{`${record.name}（ 编号：${record.code || '无'} ）`}</span>
                  </p>
                  <p>
                    <span className="bold">所在地址：</span>
                    <span>{record.address}</span>
                  </p>
                  <Divider />
                  <p>
                    <span className="bold">其他信息：</span>
                    <span>{`创建于 ${record.createTime}，最后更新于 ${record.updateTime}。`}</span>
                  </p>
                </div>
              )}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <OperateModal
          visible={updateItemVisible}
          mode="update"
          metaData={metaData}
          category={category}
          dispatch={dispatch}
          afterOK={this.afterUpdateItemModalOk}
          afterCancel={this.afterUpdateItemModalCancel}
        />
        <BackTop />
      </PageHeaderWrapperCustom>
    );
  }
}

export default List;
